package com.mszlu.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mszlu.blog.dao.ArticleDAO;
import com.mszlu.blog.dao.CommentDAO;
import com.mszlu.blog.entity.Article;
import com.mszlu.blog.entity.Comment;
import com.mszlu.blog.service.ArticleService;
import com.mszlu.blog.service.CommentService;
import com.mszlu.blog.service.ThreadPoolService;
import org.apache.tomcat.jni.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;


@Service
public class ThreadPoolServiceImpl implements ThreadPoolService {

    @Autowired
    private ArticleDAO articleDAO;

    @Autowired
    private CommentDAO commentDAO;

    @Async("taskExecutor")
    public void updateCommentCounts(Long articleId) {
        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Comment::getArticleId,articleId);
        lambdaQueryWrapper.eq(Comment::getLevel,1);
        int count = commentDAO.selectCount(lambdaQueryWrapper);

        LambdaQueryWrapper<Article> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(Article::getId,articleId);
        Article article = new Article();
        article.setCommentCounts(count+1);
        articleDAO.update(article,lambdaQueryWrapper1);
    }

    @Async("taskExecutor")
    public void updateViewCounts(Article article) {
        int viewCounts = article.getViewCounts();
        article.setViewCounts(viewCounts + 1);
        LambdaUpdateWrapper<Article> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Article::getId,article.getId());
        //设置一个 为了多线程下线程安全
        lambdaUpdateWrapper.eq(Article::getViewCounts,viewCounts);

        articleDAO.update(article, lambdaUpdateWrapper);
    }
}